package Client;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Formatter;
/**
 * calculating the file's check sum
 * @author liel && guy
 *
 */
public class Hash 
{
	/** 
	 * get a key, calculate file check sum
	 * @param fileName - the file name
	 * @return the file check sum
	 * @throws Exception
	 */
	public static String getHashFile(String fileName) throws Exception
	{
		Thread.sleep(500);
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		System.out.println("I am in Hash");
		return Hash.calculateHash(sha1, fileName);
	}
	/**
	 * Calculate a special key for each file
	 * @param algorithm
	 * @param fileName
	 * @return String
	 * @throws Exception
	 */
    public static String calculateHash(MessageDigest algorithm, String fileName) throws Exception
    {
    	new File (fileName);
    	System.out.println("The file name is "+ fileName);
//    	System.out.println("0");
    	File f = new File(fileName);
    	if (!f.exists())
    		return null;
        FileInputStream fis = new FileInputStream(fileName);
//        System.out.println("1");
        BufferedInputStream bis = new BufferedInputStream(fis);
 //       System.out.println("2");
        DigestInputStream dis = new DigestInputStream(bis, algorithm);
 //       System.out.println("3");
        while (dis.read() != -1);
 //       System.out.println("4");
        byte[] hash  = algorithm.digest();
 //       System.out.println("5");
        fis.close();
        bis.close();
        dis.close();
        return byteArray2Hex(hash);
    }
    //Convert bytes to Hex
    private static String byteArray2Hex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

}